// pages/index/index.js
import { TaskManager } from '../../utils/taskManager.js'
import { FILTER_OPTIONS } from '../../utils/constants.js'

Page({
  data: {
    tasks: [], // 原始任务列表
    filteredTasks: [], // 筛选后的任务列表
    filterType: 'all', // 筛选类型：all, high, medium, low
    filterIndex: 0, // 筛选选项索引
    filterOptions: FILTER_OPTIONS,
    loading: false, // 加载状态
    refreshing: false, // 刷新状态
    
    // 搜索相关
    showSearch: false, // 是否显示搜索栏
    searchKeyword: '', // 搜索关键词
    searchFocus: false, // 搜索框焦点状态
    
    // 排序相关
    sortIndex: 0, // 排序选项索引
    sortOptions: [
      { value: 'createTime_desc', label: '创建时间↓' },
      { value: 'createTime_asc', label: '创建时间↑' },
      { value: 'updateTime_desc', label: '更新时间↓' },
      { value: 'priority_asc', label: '优先级↑' },
      { value: 'priority_desc', label: '优先级↓' },
      { value: 'title_asc', label: '标题A-Z' }
    ],
    
    // 批量操作相关
    batchMode: false, // 批量操作模式
    selectedTasks: [], // 选中的任务ID列表
    allSelected: false // 是否全选
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    console.log('TodoList主页加载')
    this.initData()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.loadTasks()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({ refreshing: true })
    this.loadTasks()
    setTimeout(() => {
      wx.stopPullDownRefresh()
      this.setData({ refreshing: false })
    }, 1000)
  },

  /**
   * 初始化数据
   */
  initData() {
    // 检查是否需要初始化示例数据
    const result = TaskManager.initSampleData()
    if (result.success) {
      console.log('示例数据初始化成功')
      wx.showToast({
        title: '欢迎使用TodoList',
        icon: 'success'
      })
    }
    this.loadTasks()
  },

  /**
   * 加载任务列表
   */
  loadTasks() {
    this.setData({ loading: true })
    
    try {
      const tasks = TaskManager.getTasks({
        filter: 'pending',
        priority: 'all',
        sortBy: 'createTime',
        order: 'desc'
      })
      
      this.setData({
        tasks: tasks,
        loading: false
      })
      
      // 应用筛选和搜索
      this.applyFiltersAndSearch()
      
      console.log('任务列表加载成功:', tasks.length)
    } catch (error) {
      console.error('加载任务列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  /**
   * 应用筛选和搜索
   */
  applyFiltersAndSearch() {
    let filteredTasks = [...this.data.tasks]
    
    // 应用优先级筛选
    if (this.data.filterType !== 'all') {
      const priorityMap = { 'high': 1, 'medium': 2, 'low': 3 }
      filteredTasks = filteredTasks.filter(task => 
        task.priority === priorityMap[this.data.filterType]
      )
    }
    
    // 应用搜索
    if (this.data.searchKeyword.trim()) {
      const keyword = this.data.searchKeyword.trim().toLowerCase()
      filteredTasks = filteredTasks.filter(task => 
        task.title.toLowerCase().includes(keyword) ||
        (task.note && task.note.toLowerCase().includes(keyword))
      )
    }
    
    // 应用排序
    filteredTasks = this.applySorting(filteredTasks)
    
    // 为每个任务添加选中状态信息
    filteredTasks = filteredTasks.map(task => ({
      ...task,
      isSelected: this.data.selectedTasks.includes(task.id)
    }))
    
    // 计算是否全选
    const allSelected = filteredTasks.length > 0 && 
                       filteredTasks.every(task => task.isSelected)
    
    this.setData({ 
      filteredTasks,
      allSelected
    })
  },

  /**
   * 应用排序
   */
  applySorting(tasks) {
    const sortOption = this.data.sortOptions[this.data.sortIndex]
    const [field, order] = sortOption.value.split('_')
    
    return [...tasks].sort((a, b) => {
      let aValue, bValue
      
      switch (field) {
        case 'createTime':
        case 'updateTime':
          aValue = a[field] || 0
          bValue = b[field] || 0
          break
        case 'priority':
          aValue = a.priority
          bValue = b.priority
          break
        case 'title':
          aValue = a.title.toLowerCase()
          bValue = b.title.toLowerCase()
          break
        default:
          return 0
      }
      
      if (order === 'asc') {
        return aValue > bValue ? 1 : aValue < bValue ? -1 : 0
      } else {
        return aValue < bValue ? 1 : aValue > bValue ? -1 : 0
      }
    })
  },

  /**
   * 切换搜索栏显示
   */
  toggleSearch() {
    const showSearch = !this.data.showSearch
    this.setData({
      showSearch: showSearch,
      searchFocus: showSearch
    })
    
    if (!showSearch) {
      this.setData({ searchKeyword: '' })
      this.applyFiltersAndSearch()
    }
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    const keyword = e.detail.value
    this.setData({ searchKeyword: keyword })
    
    // 实时搜索
    this.applyFiltersAndSearch()
  },

  /**
   * 搜索确认
   */
  onSearchConfirm(e) {
    const keyword = e.detail.value.trim()
    if (keyword) {
      console.log('搜索关键词:', keyword)
      wx.showToast({
        title: `搜索"${keyword}"`,
        icon: 'none',
        duration: 1000
      })
    }
  },

  /**
   * 清空搜索
   */
  clearSearch() {
    this.setData({ searchKeyword: '' })
    this.applyFiltersAndSearch()
  },

  /**
   * 切换筛选类型
   */
  onFilterChange(e) {
    const filterIndex = e.detail.value
    const filterType = this.data.filterOptions[filterIndex].value
    
    this.setData({
      filterIndex: filterIndex,
      filterType: filterType
    })
    
    this.applyFiltersAndSearch()
    
    // 显示筛选结果提示
    const filterLabel = this.data.filterOptions[filterIndex].label
    wx.showToast({
      title: `显示${filterLabel}任务`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 切换排序方式
   */
  onSortChange(e) {
    const sortIndex = e.detail.value
    this.setData({ sortIndex: sortIndex })
    
    this.applyFiltersAndSearch()
    
    // 显示排序结果提示
    const sortLabel = this.data.sortOptions[sortIndex].label
    wx.showToast({
      title: `按${sortLabel}排序`,
      icon: 'none',
      duration: 1000
    })
  },

  /**
   * 切换批量操作模式
   */
  toggleBatchMode() {
    const batchMode = !this.data.batchMode
    this.setData({
      batchMode: batchMode,
      selectedTasks: [],
      allSelected: false
    })
    
    // 更新filteredTasks中的选中状态
    if (!batchMode) {
      // 退出批量模式时，清除所有选中状态
      const filteredTasks = this.data.filteredTasks.map(task => ({
        ...task,
        isSelected: false
      }))
      this.setData({ filteredTasks })
    } else {
      // 进入批量模式时，重新应用筛选以添加选中状态
      this.applyFiltersAndSearch()
    }
    
    if (batchMode) {
      wx.showToast({
        title: '进入批量操作模式',
        icon: 'none'
      })
    }
  },

  /**
   * 切换任务选择状态
   */
  toggleTaskSelection(e) {
    const taskId = e.currentTarget.dataset.id
    const selectedTasks = [...this.data.selectedTasks]
    const index = selectedTasks.indexOf(taskId)
    
    // 更新selectedTasks数组
    if (index > -1) {
      selectedTasks.splice(index, 1)
    } else {
      selectedTasks.push(taskId)
    }
    
    // 更新filteredTasks中的选中状态
    const filteredTasks = this.data.filteredTasks.map(task => ({
      ...task,
      isSelected: task.id === taskId ? !task.isSelected : task.isSelected
    }))
    
    // 计算是否全选
    const allSelected = filteredTasks.length > 0 && 
                       filteredTasks.every(task => task.isSelected)
    
    this.setData({ 
      selectedTasks,
      filteredTasks,
      allSelected
    })
    
    // 添加触觉反馈
    wx.vibrateShort()
  },

  /**
   * 全选/取消全选当前显示的任务
   */
  toggleSelectAll() {
    const filteredTasks = this.data.filteredTasks
    const selectedTasks = this.data.selectedTasks
    const allSelected = this.data.allSelected
    
    if (allSelected) {
      // 取消全选：从selectedTasks中移除当前显示的所有任务
      const visibleTaskIds = filteredTasks.map(task => task.id)
      const newSelectedTasks = selectedTasks.filter(id => !visibleTaskIds.includes(id))
      
      const updatedFilteredTasks = filteredTasks.map(task => ({
        ...task,
        isSelected: false
      }))
      
      this.setData({
        selectedTasks: newSelectedTasks,
        filteredTasks: updatedFilteredTasks,
        allSelected: false
      })
      
      wx.showToast({
        title: '已取消全选',
        icon: 'none',
        duration: 1000
      })
    } else {
      // 全选：将当前显示的所有任务添加到selectedTasks
      const visibleTaskIds = filteredTasks.map(task => task.id)
      const newSelectedTasks = [...new Set([...selectedTasks, ...visibleTaskIds])]
      
      const updatedFilteredTasks = filteredTasks.map(task => ({
        ...task,
        isSelected: true
      }))
      
      this.setData({
        selectedTasks: newSelectedTasks,
        filteredTasks: updatedFilteredTasks,
        allSelected: true
      })
      
      wx.showToast({
        title: `已选择 ${visibleTaskIds.length} 个任务`,
        icon: 'none',
        duration: 1000
      })
    }
    
    // 添加触觉反馈
    wx.vibrateShort()
  },

  /**
   * 批量完成任务
   */
  batchComplete() {
    const selectedTasks = this.data.selectedTasks
    if (selectedTasks.length === 0) {
      wx.showToast({
        title: '请先选择任务',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '批量完成',
      content: `确定要完成选中的 ${selectedTasks.length} 个任务吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' })
          
          const result = TaskManager.batchOperation(selectedTasks, 'complete')
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            // 清理批量操作状态
            this.setData({
              batchMode: false,
              selectedTasks: []
            })
            
            // 重新加载任务列表
            this.loadTasks()
            wx.vibrateShort()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 批量删除任务
   */
  batchDelete() {
    const selectedTasks = this.data.selectedTasks
    if (selectedTasks.length === 0) {
      wx.showToast({
        title: '请先选择任务',
        icon: 'none'
      })
      return
    }
    
    wx.showModal({
      title: '批量删除',
      content: `确定要删除选中的 ${selectedTasks.length} 个任务吗？此操作不可恢复！`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '删除中...' })
          
          const result = TaskManager.batchOperation(selectedTasks, 'delete')
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            // 清理批量操作状态
            this.setData({
              batchMode: false,
              selectedTasks: []
            })
            
            // 重新加载任务列表
            this.loadTasks()
            wx.vibrateShort()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 快速完成/恢复任务
   */
  quickComplete(e) {
    const taskId = e.currentTarget.dataset.id
    const task = this.data.filteredTasks.find(t => t.id === taskId)
    
    if (!task) return
    
    wx.showLoading({ title: '处理中...' })
    
    let result
    if (task.status === 1) {
      // 已完成，恢复为待完成
      result = TaskManager.uncompleteTask(taskId)
    } else {
      // 待完成，标记为已完成
      result = TaskManager.completeTask(taskId)
    }
    
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success',
        duration: 1000
      })
      
      this.loadTasks()
      wx.vibrateShort()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 点击任务项
   */
  onTaskTap(e) {
    const taskId = e.currentTarget.dataset.id
    console.log('点击任务:', taskId)
    
    // 跳转到任务详情页
    wx.navigateTo({
      url: `/pages/detail/detail?id=${taskId}`
    })
  },

  /**
   * 长按任务项
   */
  onTaskLongTap(e) {
    const taskId = e.currentTarget.dataset.id
    const task = this.data.filteredTasks.find(t => t.id === taskId)
    
    if (!task) {
      wx.showToast({
        title: '任务不存在',
        icon: 'error'
      })
      return
    }
    
    const actionItems = ['编辑', '删除']
    if (task.status === 1) {
      actionItems.unshift('恢复为待完成')
    } else {
      actionItems.unshift('标记完成')
    }
    
    wx.showActionSheet({
      itemList: actionItems,
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            if (task.status === 1) {
              this.uncompleteTask(task)
            } else {
              this.completeTask(task)
            }
            break
          case 1:
            this.editTask(task)
            break
          case 2:
            this.deleteTask(task)
            break
        }
      }
    })
  },

  /**
   * 编辑任务
   */
  editTask(task) {
    console.log('编辑任务:', task.id)
    // 跳转到编辑页面
    wx.navigateTo({
      url: `/pages/detail/detail?id=${task.id}&mode=edit`
    })
  },

  /**
   * 完成任务
   */
  completeTask(task) {
    wx.showLoading({
      title: '处理中...'
    })
    
    const result = TaskManager.completeTask(task.id)
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success'
      })
      
      // 刷新任务列表
      this.loadTasks()
      
      // 触发页面振动反馈
      wx.vibrateShort()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 恢复任务为待完成
   */
  uncompleteTask(task) {
    wx.showLoading({
      title: '处理中...'
    })
    
    const result = TaskManager.uncompleteTask(task.id)
    wx.hideLoading()
    
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'success'
      })
      
      // 刷新任务列表
      this.loadTasks()
    } else {
      wx.showToast({
        title: result.message,
        icon: 'error'
      })
    }
  },

  /**
   * 删除任务
   */
  deleteTask(task) {
    wx.showModal({
      title: '确认删除',
      content: `确定要删除任务"${task.title}"吗？`,
      confirmText: '删除',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '删除中...'
          })
          
          const result = TaskManager.deleteTask(task.id)
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            // 刷新任务列表
            this.loadTasks()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 创建新任务
   */
  createTask() {
    if (this.data.batchMode) {
      this.toggleBatchMode()
      return
    }
    
    console.log('创建新任务')
    // 跳转到创建页面
    wx.navigateTo({
      url: '/pages/detail/detail'
    })
  },

  /**
   * 清空所有任务（测试功能）
   */
  clearAllTasks() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有任务吗？此操作不可恢复！',
      confirmText: '清空',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '清空中...'
          })
          
          const result = TaskManager.clearAllTasks()
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: result.message,
              icon: 'success'
            })
            
            // 刷新任务列表
            this.loadTasks()
          } else {
            wx.showToast({
              title: result.message,
              icon: 'error'
            })
          }
        }
      }
    })
  },

  /**
   * 重新初始化示例数据（测试功能）
   */
  resetSampleData() {
    wx.showModal({
      title: '重置数据',
      content: '确定要重置为示例数据吗？当前数据将被清空！',
      confirmText: '重置',
      confirmColor: '#ff4757',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '重置中...'
          })
          
          // 先清空所有任务
          TaskManager.clearAllTasks()
          
          // 再初始化示例数据
          const result = TaskManager.initSampleData()
          wx.hideLoading()
          
          if (result.success) {
            wx.showToast({
              title: '数据重置成功',
              icon: 'success'
            })
            
            // 刷新任务列表
            this.loadTasks()
          } else {
            wx.showToast({
              title: '数据重置失败',
              icon: 'error'
            })
          }
        }
      }
    })
  }
}) 